#include "stdafx.h"
#include <windows.h>
#include "ioal.h"

using namespace System::Runtime::InteropServices;

namespace IOAL {
	ioal::ioal(unsigned short port, String^ server)
	{
		IntPtr s = Marshal::StringToHGlobalAnsi(server);
		m_ioal=ioal_create(port, static_cast<const char*>(s.ToPointer()));
	}

	void ioal::login()
	{
		ioal_login_async(m_ioal);
		//ioal_login(m_ioal);
	}

	bool ioal::old()
	{
		return ioal_old(m_ioal);
	}

	int ioal::status()
	{
		return ioal_status(m_ioal);
	}

	int ioal::error_code()
	{
		return ioal_error_code(m_ioal);
	}

	void ioal::begin_game()
	{
		ioal_begin_game(m_ioal);
	}

	void ioal::end_game()
	{
		ioal_end_game(m_ioal);
	}

	void ioal::logout()
	{
		ioal_logout(m_ioal);
	}

	int ioal::login_progress()
	{
		return ioal_login_progress(m_ioal);
	}

	int ioal::online_players()
	{
		return ioal_online_players(m_ioal);
	}

	String^ ioal::status_string()
	{
		const char* s=ioal_status_string(m_ioal);
		return gcnew String(s);
	}

	String^ ioal::error_string()
	{
		const char* s=ioal_error_string(m_ioal);
		return gcnew String(s);
	}

	void ioal::callback_handler()
	{
		IAsyncResult^ r=m_control->BeginInvoke(m_state_change_handler);
	}

	public delegate void CallbackHandler();
	void ioal::state_change_handler(Control^ c, IGUI::onStateChange^ h)
	{
		m_control=c;
		m_state_change_handler=h;

		CallbackHandler^ cb=gcnew CallbackHandler(this, &ioal::callback_handler);
		m_gch=GCHandle::Alloc(cb);
		IntPtr ip=Marshal::GetFunctionPointerForDelegate(cb);
		ioal_on_state_change(m_ioal, static_cast<void(*)()>(ip.ToPointer()));
	}

	String^ ioal::get_information(int item)
	{
		const char* rst=ioal_get_information(m_ioal, (IOAL_Information)item);
		return gcnew String(rst);
	}
}

